package com.ruoyi.tranShort.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.tranShort.mapper.ShortSchedulingTaskMapper;
import com.ruoyi.tranShort.domain.ShortSchedulingTask;
import com.ruoyi.tranShort.service.IShortSchedulingTaskService;

/**
 * 排班任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-08-17
 */
@Service("shortSchedulingTaskService")
public class ShortSchedulingTaskServiceImpl implements IShortSchedulingTaskService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ShortSchedulingTaskServiceImpl.class);
    @Autowired
    private ShortSchedulingTaskMapper shortSchedulingTaskMapper;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 提前时间分钟
     */
    public static int leadTime = 0;
    /**
     * 超时时间 分钟
     */
    @Value("${task.timeOutTime}")
    private int timeOutTime;

    /**
     * 查询排班任务
     * 
     * @param id 排班任务主键
     * @return 排班任务
     */
    @Override
    public ShortSchedulingTask selectShortSchedulingTaskById(String id)
    {
        return shortSchedulingTaskMapper.selectShortSchedulingTaskById(id);
    }

    /**
     * 查询排班任务列表
     * 
     * @param shortSchedulingTask 排班任务
     * @return 排班任务
     */
    @Override
    public List<ShortSchedulingTask> selectShortSchedulingTaskList(ShortSchedulingTask shortSchedulingTask)
    {
        return shortSchedulingTaskMapper.selectShortSchedulingTaskList(shortSchedulingTask);
    }

    /**
     * 新增排班任务
     * 
     * @param shortSchedulingTask 排班任务
     * @return 结果
     */
    @Override
    public int insertShortSchedulingTask(ShortSchedulingTask shortSchedulingTask)
    {
        shortSchedulingTask.setCreateTime(DateUtils.getNowDate());
        return shortSchedulingTaskMapper.insertShortSchedulingTask(shortSchedulingTask);
    }

    /**
     * 修改排班任务
     * 
     * @param shortSchedulingTask 排班任务
     * @return 结果
     */
    @Override
    public int updateShortSchedulingTask(ShortSchedulingTask shortSchedulingTask)
    {
        return shortSchedulingTaskMapper.updateShortSchedulingTask(shortSchedulingTask);
    }

    /**
     * 批量删除排班任务
     * 
     * @param ids 需要删除的排班任务主键
     * @return 结果
     */
    @Override
    public int deleteShortSchedulingTaskByIds(String[] ids)
    {
        return shortSchedulingTaskMapper.deleteShortSchedulingTaskByIds(ids);
    }

    /**
     * 删除排班任务信息
     * 
     * @param id 排班任务主键
     * @return 结果
     */
    @Override
    public int deleteShortSchedulingTaskById(String id)
    {
        return shortSchedulingTaskMapper.deleteShortSchedulingTaskById(id);
    }

    @Override
    public int addTask(Long schedulingDateId, String startTimeQuantum, String endTimeQuantum, Date executeTime,Long schedulingId) {
        ShortSchedulingTask shortSchedulingTask = new ShortSchedulingTask();
        shortSchedulingTask.setSchedulingId(schedulingId);
        shortSchedulingTask.setCreateTime(DateUtils.getNowDate());
        StringBuilder functionStrBuilder = new StringBuilder();
        functionStrBuilder.append("wristletService").append(".").append("executeWristlet").append("(").append(schedulingDateId).append("L").append(",").append(startTimeQuantum).append(",").append(endTimeQuantum).append(")");
        shortSchedulingTask.setTaskExecuteFunction(functionStrBuilder.toString());
        //时间格式解析
        String[] startTimeQuantumSplit = startTimeQuantum.split(":");
        String[] endTimeQuantumSplit = endTimeQuantum.split(":");
        if(startTimeQuantum.length() == 1){
            startTimeQuantum = "0"+startTimeQuantum;
        }
        if(endTimeQuantum.length() == 1){
            endTimeQuantum = "0"+endTimeQuantum;
        }
        //补位数操作
        for (int i = 0; i < 3 - startTimeQuantumSplit.length; i++) {
            startTimeQuantum =startTimeQuantum+":00";
        }
        for (int i = 0; i < 3 - endTimeQuantumSplit.length; i++) {
            endTimeQuantum =endTimeQuantum+":00";
        }
        Date startDateTime = null;
        try {
            startDateTime = simpleDateTimeFormat.parse(simpleDateFormat.format(executeTime) + " " + startTimeQuantum);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        shortSchedulingTask.setTaskExecuteTime(startDateTime);
        String taskName = simpleDateFormat.format(executeTime)+":"+startTimeQuantum+"-"+endTimeQuantum;
        shortSchedulingTask.setTaskName(taskName);
        shortSchedulingTask.setTaskStatus(0L);
        int i = shortSchedulingTaskMapper.insertShortSchedulingTask(shortSchedulingTask);
        return i;
    }

    /**
     * 任务执行
     */
    @Override
    public void taskExecute(){
        LOGGER.info("定时任务执行====================");
        //获取当前时间
        Date nowDate = DateUtils.getNowDate();
        long leadDateTime = nowDate.getTime() - leadTime * 60 * 1000;
        Date leadDate = new Date(leadDateTime);
        //查询出数据库，当前最近的任务
         ShortSchedulingTask shortSchedulingTask = new ShortSchedulingTask();
        shortSchedulingTask.setTaskStatus(0L);
        shortSchedulingTask.setTaskExecuteTime(leadDate);
        List<ShortSchedulingTask> shortSchedulingTaskList = shortSchedulingTaskMapper.selectScheduingTaskTime(shortSchedulingTask);
        for (ShortSchedulingTask schedulingTask : shortSchedulingTaskList) {
            //判断任务间隔时间，超过指定执行，还未执行的判定未执行失败
            Date taskExecuteTime = schedulingTask.getTaskExecuteTime();
            long time = taskExecuteTime.getTime();

            if((leadDateTime/(60*1000)-time/(60*1000))>=timeOutTime){
                //更新状态
                schedulingTask.setTaskStatus(2L);
                shortSchedulingTaskMapper.updateShortSchedulingTask(schedulingTask);
            }else{
                //执行任务
                //更新状态
                schedulingTask.setTaskStatus(1L);
                shortSchedulingTaskMapper.updateShortSchedulingTask(schedulingTask);
                //解析bean
                String taskExecuteFunction = schedulingTask.getTaskExecuteFunction();

                String[] taskExecuteFunctionSplit = taskExecuteFunction.split("\\.");
                String beanName = taskExecuteFunctionSplit[0];
                String methodStr = taskExecuteFunctionSplit[1];
                String[] methodStrSplit = methodStr.split("\\(");
                //方法名称
                String methodName = methodStrSplit[0];
                String paramStr = methodStrSplit[1].replace(")", "");
                //参数列表
                String[] paramArr = paramStr.split(",");
                Object[] objects = new Object[paramArr.length];
                for (int i = 0; i < paramArr.length; i++) {
                    boolean longStrBoll = paramArr[i].contains("L");
                    if(longStrBoll){
                        long aLong = Long.parseLong(paramArr[i].replace("L",""));
                        objects[i] = aLong;
                    } else{
                        objects[i] = paramArr[i];
                    }
                }

                Object bean = SpringUtils.getBean(beanName);
                if(bean == null){
                    break;
                }
                Class<?> clazz = bean.getClass();
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    String name = method.getName();
                    if(name.equals(methodName)){
                        //执行
                        try {
                            Object invoke = method.invoke(bean, objects);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    public int deleteTask(Long schedulingDateId, String startTimeQuantum, String endTimeQuantum, Date executeTime, Long schedulingId) {
        //时间格式解析
        String[] startTimeQuantumSplit = startTimeQuantum.split(":");
        String[] endTimeQuantumSplit = endTimeQuantum.split(":");
        if(startTimeQuantum.length() == 1){
            startTimeQuantum = "0"+startTimeQuantum;
        }
        if(endTimeQuantum.length() == 1){
            endTimeQuantum = "0"+endTimeQuantum;
        }
        //补位数操作
        for (int i = 0; i < 3 - startTimeQuantumSplit.length; i++) {
            startTimeQuantum =startTimeQuantum+":00";
        }
        for (int i = 0; i < 3 - endTimeQuantumSplit.length; i++) {
            endTimeQuantum =endTimeQuantum+":00";
        }

        String taskName = simpleDateFormat.format(executeTime)+":"+startTimeQuantum+"-"+endTimeQuantum;
        int i = shortSchedulingTaskMapper.deleteShortSchedulingTaskBySchedulingIdAndTaskName(schedulingId, taskName);
        return i;
    }

    /**
     * 修改时间
     * @param schedulingDateId
     * @param oldTimeQuantum
     * @param newTimeQuantum
     * @param executeTime
     * @param schedulingId
     * @return
     */
    @Override
    public int updateTask(Long schedulingDateId, String oldTimeQuantum, String newTimeQuantum, Date executeTime, Long schedulingId) {
        //时间格式解析
        String[] oldSplit = oldTimeQuantum.split("-");
        String[] oldStartTimeQuantumSplit = oldSplit[0].split(":");
        String[] oldEndTimeQuantumSplit = oldSplit[1].split(":");
        if(oldSplit[0].length() == 1){
            oldSplit[0] = "0"+oldSplit[0];
        }
        if(oldSplit[1].length() == 1){
            oldSplit[1] = "0"+oldSplit[1];
        }
        //补位数操作
        for (int i = 0; i < 3 - oldStartTimeQuantumSplit.length; i++) {
            oldSplit[0] =oldSplit[0]+":00";
        }
        for (int i = 0; i < 3 - oldEndTimeQuantumSplit.length; i++) {
            oldSplit[1] =oldSplit[1]+":00";
        }

        String oldTaskName = simpleDateFormat.format(executeTime)+":"+oldSplit[0]+"-"+oldSplit[1];
        //根据 taskName和schedulingId查询
        ShortSchedulingTask shortSchedulingTask = shortSchedulingTaskMapper.selectSchedulingTaskByTaskNameAndSchedulingId(schedulingId, oldTaskName);
        //更新
        //时间格式解析
        String[] newSplit = newTimeQuantum.split("-");
        String[] newStartTimeQuantumSplit = newSplit[0].split(":");
        String[] newEndTimeQuantumSplit = newSplit[1].split(":");
        if(newSplit[0].length() == 1){
            newSplit[0] = "0"+newSplit[0];
        }
        if(newSplit[1].length() == 1){
            newSplit[1] = "0"+newSplit[1];
        }
        //补位数操作
        for (int i = 0; i < 3 - newStartTimeQuantumSplit.length; i++) {
            newSplit[0] =newSplit[0]+":00";
        }
        for (int i = 0; i < 3 - newEndTimeQuantumSplit.length; i++) {
            newSplit[1] =newSplit[1]+":00";
        }
        String newTaskName = simpleDateFormat.format(executeTime)+":"+newSplit[0]+"-"+newSplit[1];
        shortSchedulingTask.setTaskName(newTaskName);
        StringBuilder functionStrBuilder = new StringBuilder();
        String[] split = newTimeQuantum.split("-");
        functionStrBuilder.append("wristletService").append(".").append("executeWristlet").append("(").append(schedulingDateId).append("L").append(",").append(split[0]).append(",").append(split[1]).append(")");
        shortSchedulingTask.setTaskExecuteFunction(functionStrBuilder.toString());
        Date startDateTime = null;
        try {
            startDateTime = simpleDateTimeFormat.parse(simpleDateFormat.format(executeTime) + " " + newSplit[0]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        shortSchedulingTask.setTaskExecuteTime(startDateTime);

        int i = shortSchedulingTaskMapper.updateShortSchedulingTask(shortSchedulingTask);
        return i;
    }
}
